﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

using System.IO;

namespace SFR
{
    public partial class Import : Form
    {
        OpenFileDialog openFileDialog1;

        MongoDbHelper mdb;

        BackgroundWorker bw;

        int filesProccessed;

        public delegate void ImportEventHandler(object sender, EventArgs e);

        public event ImportEventHandler ImportCompleted;

        Dictionary<string,bool> TagsPerDocument;

        public Import(MongoDbHelper db)
        {
            InitializeComponent();

            mdb = db;
            openFileDialog1 = new OpenFileDialog();
            openFileDialog1.Multiselect = true;
            toolStripStatusLabel1.Text = "Ready!";

            bw = new BackgroundWorker();
            bw.WorkerSupportsCancellation = true;
            bw.WorkerReportsProgress = true;
            bw.DoWork += new DoWorkEventHandler(bw_DoWork);
            bw.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bw_RunWorkerCompleted);
            bw.ProgressChanged += new ProgressChangedEventHandler(bw_ProgressChanged);

            TagsPerDocument = new Dictionary<string,bool>();
        }

        void bw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            buttonStart.Text = "Start";

            if ((e.Cancelled == true))
            {
                toolStripStatusLabel1.Text = "Uploaded: " + filesProccessed + "/" + openFileDialog1.FileNames.Length;
                System.Windows.Forms.MessageBox.Show("Upload cancelled!");
            }

            else if (!(e.Error == null))
            {
                toolStripStatusLabel1.Text = "Uploaded: " + filesProccessed + "/" + openFileDialog1.FileNames.Length;
                System.Windows.Forms.MessageBox.Show("Error while uploading: " + e.Error);
            }

            else
            {
                progressBar1.Value = 100;
                toolStripStatusLabel1.Text = "Import successful. Uploaded: " + filesProccessed + "/" + openFileDialog1.FileNames.Length;
            }

            if (filesProccessed > 0) ImportCompleted(null, null);
            buttonStart.Enabled = true;
            buttonStart.Text = "Start";
        }

        void bw_DoWork(object sender, DoWorkEventArgs e)
        {
            filesProccessed = 0;
            toolStripStatusLabel1.Text = "Import started, please wait ...";

            foreach (string fname in openFileDialog1.FileNames)
            {
                if ((bw.CancellationPending == true))
                {
                    e.Cancel = true;
                    break;
                }

                FileInfo f = new FileInfo(fname);

                Doc doc = new Doc();
                doc.DocName = f.Name;
                doc.Comment = textBox4.Text;
                doc.SubjectName = textBox5.Text;
                doc.Tags = GetSelectedTags(treeView1);
                doc.FileSizeKb = f.Length/1024;

                mdb.ImportFile(doc, fname);
                filesProccessed++;

                bw.ReportProgress(filesProccessed * (100 / openFileDialog1.FileNames.Length), "Uploaded (" + filesProccessed + "/" + openFileDialog1.FileNames.Length + "): \"" + f.Name + "\"...");
            }

        }

        private void buttonBrowse_Click(object sender, EventArgs e)
        {
            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                this.textBox1.Text = "";

                foreach (string s in openFileDialog1.FileNames)
                {
                    FileInfo f = new FileInfo(s);
                    this.textBox1.Text += "\""+f.Name+"\" ";
                }
                
            }
        }

        private void buttonStart_Click(object sender, EventArgs e)
        {
            if (bw.IsBusy)
            {
                buttonStart.Enabled = false;
                bw.CancelAsync();
            }
            else
            {
                //input check
                foreach (string fname in openFileDialog1.FileNames)
                {
                    FileInfo f;
                    try
                    {
                        f = new FileInfo(fname);
                    }
                    catch (Exception ex)
                    {
                        System.Windows.Forms.MessageBox.Show("Error: invalid file: " + fname); return;
                    }

                    if (!f.Exists) { System.Windows.Forms.MessageBox.Show("Error: The file you have selected does not exist!"); continue; }
                }

                progressBar1.Value = 0;
                buttonStart.Text = "Cancel";
                bw.RunWorkerAsync();
            }
        }

        void bw_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            progressBar1.Value = (int)e.ProgressPercentage;
            toolStripStatusLabel1.Text = (string)e.UserState;
        }

        public Dictionary<string,bool> GetSelectedTags(TreeView tree)
        {
            TagsPerDocument.Clear();
            ListNodes(tree.Nodes[0]);
            return TagsPerDocument;
        }

        void ListNodes(TreeNode node)
        {
            if (node.Checked)
                TagsPerDocument.Add(node.Level + "->" + node.Name,true);

            foreach (TreeNode subnode in node.Nodes)
            {
                ListNodes(subnode);
            }
            // Print out node
        }

        private void Import_Load(object sender, EventArgs e)
        {

        }
    }
}
